package com.qf.controller;

import com.alibaba.fastjson.JSON;
import com.qf.pojo.Goods;
import com.qf.service.GoodsService;
import com.qf.service.impl.GoodsServiceImpl;
import com.qf.utils.SYS;
import com.qf.vo.ShopCart;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by Administrator on 2021/10/27.
 */
@WebServlet("/cart")
public class CartController extends BaseController {
    private GoodsService goodsService=new GoodsServiceImpl();

    public String show(HttpServletRequest request, HttpServletResponse response){

        return "";
    }
    public String add(HttpServletRequest request, HttpServletResponse response){
        //接收商品编号；
        String gids=request.getParameter("gid");
        int gid=Integer.valueOf(gids);
        Goods goods=goodsService.selectOneById(gid);//根据商品编号获得商品
        //加入购物车
        //从session中取出购物车，如果取不到，自己创建
        ShopCart shopCart=new ShopCart();//用作购物车类

        HttpSession session=request.getSession();
        Object obj=session.getAttribute(SYS.CART);//尝试从session中取出购物车
        if(obj!=null && obj instanceof ShopCart){
            //取出购物车
            shopCart=(ShopCart)obj;
        }

        shopCart.addCart(goods);
        session.setAttribute(SYS.CART,shopCart);
//        JSON.toJSONString()
        return "{\"code\":1,\"msg\":\"加入购物车成功！\"}";
    }
}
